package com.hqyj.onlineExamination.modules.common.service.impl;

import com.hqyj.onlineExamination.modules.common.dao.ExceptionLogDao;
import com.hqyj.onlineExamination.modules.common.entity.ExceptionLog;
import com.hqyj.onlineExamination.modules.common.entity.ResultEntity;
import com.hqyj.onlineExamination.modules.common.service.ExceptionLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class ExceptionLogServiceImpl implements ExceptionLogService {

    @Autowired
    private ExceptionLogDao exceptionLogDao;

    //插入
    @Override
    @Transactional
    public ResultEntity<ExceptionLog> insertExceptionLog(ExceptionLog exceptionLog) {
        List<ExceptionLog> exceptionLogs = Optional
                .ofNullable(    //dao层查询结果不为空，则返回其查询内容
                    exceptionLogDao.getExceptionLogsBy(
                        exceptionLog.getPath(), exceptionLog.getExceptionType())
                ).orElse(Collections.emptyList());  //为空，返回一个空的收集器
        if (exceptionLogs.isEmpty()) {  //为空，进行插入操作
            exceptionLog.setCreateDate(LocalDateTime.now());//由于是mybatis框架，所以需要手动设置create_date字段
            exceptionLogDao.insertExceptionLog(exceptionLog);
            return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.status,
                    "Insert successs.", exceptionLog);
        }
        //不为空，就不用插入了
        return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.status,
                "Exeption info is exist.", exceptionLog);
    }

    //查询
    @Override
    public List<ExceptionLog> getExceptionLogsBy(String path, String exceptionType) {
        return exceptionLogDao.getExceptionLogsBy(path, exceptionType);
    }
}
